import axios from './axios-miniprogram'

// axios.defaults.withCredentials = false
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8;';

axios.interceptors.request.use(function (config) {
	if(config.method == 'POST'){
		let d = ''
		for (let it in config.data) {
			d += encodeURIComponent(it) + '=' + encodeURIComponent(config.data[it]) + '&'
		}
		d = d.substring(0, d.lastIndexOf('&'));
		config.data = d
	}
  return config
}, function (error) {
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
	if(response.status == 523 || response.data.status == 523){
		console.log('must be signin! url:', response)
	}
  return response
})

class HttpClient {
	constructor() {}
	// post请求调用  
	post(url, params, onSuccess, onFailed) {
		let app = getApp()
		let _url = url.toLowerCase().indexOf('http') == 0 ? url : app.globalData.API_URL + url
		if(app.globalData.NETWORK_LIB == 'axios'){
			this.axiosRequest(_url, params, "POST", onSuccess, onFailed)
		}else{
			this.request(_url, params, "POST", onSuccess, onFailed)
		}
	}
	// get请求
	get(url, params, onSuccess, onFailed) {
		let app = getApp()
		let _url = url.toLowerCase().indexOf('http') == 0 ? url : app.globalData.API_URL + url
		
		if(app.globalData.NETWORK_LIB == 'axios'){
			this.axiosRequest(_url, params, "GET", onSuccess, onFailed)
		}else{
			this.request(_url, params, "GET", onSuccess, onFailed)
		}
	}
	// delete请求调用  
	delete(url, params, onSuccess, onFailed) {
		let app = getApp()
		let _url = url.toLowerCase().indexOf('http') == 0 ? url : app.globalData.API_URL + url
		if(app.globalData.NETWORK_LIB == 'axios'){
			this.axiosRequest(_url, params, "DELETE", onSuccess, onFailed)
		}else{
			this.request(_url, params, "DELETE", onSuccess, onFailed)
		}
	}
	// patch请求调用  
	patch(url, params, onSuccess, onFailed) {
		let app = getApp()
		let _url = url.toLowerCase().indexOf('http') == 0 ? url : app.globalData.API_URL + url
		if(app.globalData.NETWORK_LIB == 'axios'){
			this.axiosRequest(_url, params, "PATCH", onSuccess, onFailed)
		}else{
			this.request(_url, params, "POST", onSuccess, onFailed)
		}
	}

	axiosRequest(url, params, method, onSuccess, onFailed){
		let nonShowLoading = params && params.noLoading
		if(nonShowLoading) delete params.noLoading
		if(!nonShowLoading) wx.showLoading({
			mask: true
		})		
		axios({
			method: method,
			url: url,
			params: method == "GET" ? params : {},
			data: method == "POST" ? params : {},
		}).then((res) => {
			wx.hideLoading()
			if(res.status != 200){
				onFailed({
					msg: "request failed, error code:"+res.status, 
					msgDetail:{url: url,params: params, statusCode: res.status}, 
					error: res
				})
				return
			}
			onSuccess(res)	
		}).catch((err) => {
			wx.hideLoading()
			let title = "request failed!"
				if(err && err.errMsg && err.errMsg.indexOf('timeout') >= 0){
					title = "request timeout!" //failure for timeout
				}
				onFailed({
					msg: title, 
					msgDetail:{url: url, params: params,statusCode: err ? err.status : ''}, 
					error: err
				}) //failure for other reasons
		})
	}

	/**
	 * function: 封装网络请求
	 * @url URL地址
	 * @params 请求参数
	 * @method 请求方式：GET/POST
	 * @onSuccess (func)成功回调
	 * @onFailed  (func)失败回调
	 */
	request(url, params, method, onSuccess, onFailed){
		let nonShowLoading = params && params.noLoading
		if(nonShowLoading) delete params.noLoading
		if(!nonShowLoading) wx.showLoading({
			mask: true
		})
		let header = getApp().header()
		wx.request({
			url: url,
			data: this.resolveParams(params),
			method: method,
			header: header,
			success: res => {
				wx.hideLoading()
				if(res.statusCode != 200){
					onFailed({
						msg: "request failed, error code:" + res.statusCode, 
						msgDetail: { url: url,params: params, statusCode: res.statusCode }, 
						error: res
					})
					return
				} else if (res.data.status == 523) { // if user is not sign in
					console.log("sign in to access: ", url)
				}
				onSuccess(res)	
			},
			fail: err => {
				let title = "request failed!"
				if(err && err.errMsg && err.errMsg.indexOf('timeout') >= 0){
					title = "request timeout!" // failure for timeout
				}
				onFailed({
					msg: title, 
					msgDetail:{url: url, params: params,statusCode: err ? err.statusCode : ''}, 
					error: err
				}) // failure for other reasons
			}
		})
	}

	// 处理参数
	resolveParams(params){
		if (typeof params == 'undefined') params = { json: "✓" }
		if (typeof params.json == 'undefined' && "") params.json = "✓"
		return params;
	}
}

module.exports = HttpClient